import axios from 'axios'
import utils from '@/utils/utils'
import { ElMessage } from 'element-plus'
import { generateSign } from '@/utils/sign'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL, // api 的 base_url
  timeout: +import.meta.env.VITE_APP_REQUEST_TIME_OUT // 请求超时时间
})

service.interceptors.request.use(config => {
  const paramsObj = config.params || {}
  const paramsArr = Object.keys(paramsObj)
    .filter(key => paramsObj[key] != null)
    .map(key => key + '=' + paramsObj[key])
  const token = localStorage.getItem('authorization')
  const signHeaders = {
    'body-string': '',
    'query-string': encodeURI(paramsArr.join('&')),
    'x-nonce': `${utils.getRandomId()}`,
    'x-timestamp': `${new Date().getTime()}`
  }
  if (config.data) {
    signHeaders['body-string'] = encodeURIComponent(JSON.stringify(config.data))
  }
  // add api sign
  config.headers.sign = generateSign(JSON.stringify(signHeaders))
  if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.authorization = token
  }
  Object.assign(config.headers, signHeaders)
  return config
}, error => Promise.reject(error))

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const data = response.data
    if (response.headers['content-type'] != 'application/json') {
      return data
    }
    if (data.code != 200) {
      ElMessage({
        message: data.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }
    return data
  },
  error => {
    console.log('err' + error) // for debug
    ElMessage({
      message: error.response?.data.errMsg ?? '服务器错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
